package com.xyy.saas.payment.trace;

import com.xyy.saas.payment.util.AlarmUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

@Component
@Slf4j
public class AlarmService {
    @Value("${alarm.switch:true}")
    private Boolean alarmSwitch;
    @Value("${tracelog.webChatWebHook}")
    private String webChatWebHook;
    @Value("${tracelog.webChatMobiles:18231176459}")
    private String webChatMobiles;

    public static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 5, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(800),
            r -> new Thread(r, "AlarmService" + r.hashCode()), new ThreadPoolExecutor.DiscardPolicy()); // 线程池饱和策略：直接丢弃

    public void alarm(DingTalkMessage msg) {
        alarm(webChatWebHook, webChatMobiles, msg);
    }

    public void alarm(String webChatWebHook, String webChatMobiles, DingTalkMessage msg) {
        try {
            if (!alarmSwitch) {
                return;
            }
            CompletableFuture.runAsync(() -> {
                try {
                    AlarmUtil.sendMsg(webChatWebHook, webChatMobiles, msg.toString());
                } catch (Exception e) {
                    log.error("微信告警异常:{}", e);
                }
            }, executor);
        } catch (Exception e) {
            log.error("微信告警异常:{}", e);
        }
    }

    public void asyncAlarm(String type, String method, String msg, String param) {
        DingTalkMessage talkMessage = DingTalkMessage.builder()
                .type(type)
                .method(method)
                .msg(msg)
                .param(param).build();
        alarm(talkMessage);
    }

    public void asyncAlarm(String type, String param) {
        DingTalkMessage talkMessage = DingTalkMessage.builder()
                .type(type)
                .param(param).build();
        alarm(talkMessage);
    }
    public void asyncAlarm(String webChatWebHook, String webChatMobiles, String type, String method, String msg, String param) {
        DingTalkMessage talkMessage = DingTalkMessage.builder()
                .type(type)
                .method(method)
                .msg(msg)
                .param(param).build();
        alarm(webChatWebHook, webChatMobiles, talkMessage);
    }
}
